<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
    <style>
      th{
        width: 150px
      }
      td{
        text-align: center;
      }
      img{
        width: 100px;
      }
    </style>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
      // 添加请求拦截器
      axios.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
        //带着获取到的token添加请求
        const token = localStorage.getItem('token')
        config.headers.Authorization = `Bearer ${token}`
        return config;
      }, function (error) {
        // 对请求错误做些什么
        //如果token失效
        if(error.response.status === 401){
          localStorage.removeItem("token")
          location.href = '/login'
        }
        return Promise.reject(error);
      });
  
      // 添加响应拦截器
      axios.interceptors.response.use(function (response) {
        // 对响应数据做点什么
        //存储token
        const { authorization } = response.headers
        if(authorization){
          localStorage.setItem("token",authorization)
        }
        
        return response;
      }, function (error) {
        // 对响应错误做点什么
        return Promise.reject(error);
      });
    </script>
  </head>
  <body>
    <h1>
      后台系统-用户管理业务
      <button id="exit">退出登录</button>
    </h1>
    <div>
      <div>用户名: <input id="username" /></div>
      <div>密码: <input type="password" id="password" /></div>
      <div>年龄: <input type="number" id="age" /></div>
      <!-- input里面加上multiple的话就是上传多张图片,改了前端后端也要改 -->
      <div>头像: <input type="file" id="avatar" /></div>
      <div><button id="register">注册</button></div>
      <hr>
      <div>
        <button id="update">更新用户</button>
        <button id="delete">删除用户</button>
      </div>
      <table>
        <thead>
          <tr>
            <th>id</th>
            <th>用户名</th>
            <th>年龄</th>
            <th>头像</th>
          </tr>
        </thead>
        <tbody id="list">
          
        </tbody>
      </table>
    </div>

    <script>
      var register = document.getElementById('register');
      var update = document.getElementById('update');
      var isDelete = document.getElementById('delete');
      var username = document.getElementById('username');
      var password = document.getElementById('password');
      var age = document.getElementById('age');
      var exit = document.getElementById('exit');
      var avatar = document.getElementById('avatar');
      
      exit.onclick = ()=>{
        // fetch('/api/logout').then(res=>res.json()).then(res=>{
        //   if(res.ok === 1){
        //     location.href = '/login'
        //   }
        // })
        localStorage.removeItem("token")
        location.href = '/login'
      }
      //添加数据
      register.onclick = ()=>{
        console.log(username.value, password.value, age.value, avatar.files[0])
        // fetch("/api/user",{
        //   method: "POST",
        //   headers: {
        //     "Content-Type": "application/json"
        //   },
        //   body: JSON.stringify({
        //     username: username.value,
        //     password: password.value,
        //     age: age.value
        //   })
        // }).then(res=>res.json()).then(res=>{
        //   if(res.ok === 0){
        //     location.href = '/login'
        //   }
        //   username.value = "",
        //   password.value="",
        //   age.value = ""
        //   gainList()
        //   console.log(res)
        // })
        
        // axios.post('/api/user',{
        //   username: username.value,
        //   password: password.value,
        //   age: age.value
        // }).then(res=>{
        //   console.log(res.data)
        // })

        //创建表单实例,可以方便的将数据发送到服务器
        const formsdata = new FormData();
        formsdata.append("username", username.value);
        formsdata.append("password", password.value);
        formsdata.append("age", age.value);
        formsdata.append("avatar", avatar.files[0]);
        axios.post("/api/user",formsdata,{
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res=>{
          console.log(res.data)
        })
      }
        
      //更新数据
      update.onclick = ()=>{
        // fetch("/api/user/67068a60a2a1ad0cc0aa26ab	",{
        //   method: "PUT",
        //   headers: {
        //     "Content-Type": "application/json"
        //   },
        //   body: JSON.stringify({
        //     username: "修改的名字",
        //     password: "修改的密码",
        //     age: 2
        //   })
        // }).then(res=>res.json()).then(res=>{
        //   console.log(res)
        //   gainList()
        // })
        axios.put('/api/user/67068a60a2a1ad0cc0aa26ab',{
          username: "修改的名字",
          password: "修改的密码",
          age: 2
        }).then(res=>{
          console.log(res.data)
        })
      }

      
      //删除数据
      isDelete.onclick = ()=>{
        // console.log(username.value, password.value, age.value)
        // fetch("/api/user/67068a2bd66f9b7d27740371",{
        //   method: "DELETE",
        //   headers: {
        //     "Content-Type": "application/json"
        //   }
        // })
        // .then(res=>res.json()).then(res=>{
        //   console.log(res)
        //   gainList()
        // })
        axios.delete('/api/user/67068a2bd66f9b7d27740371').then(res=>{
          console.log(res.data)
        })
      }

     //获取列表
      function gainList(){
        //获取列表
          fetch("/api/user/list?page=1&limit=50").then(res=>res.json()).then(res=>{
            console.log(res)
            var list = document.getElementById('list');
            list.innerHTML = res.data.map(item=>`
              <tr>
                <td>${item._id}</td>
                <td>${item.username}</td>
                <td>${item.age}</td>  
                <td><img src=${item.avatar} /></td>
                <td ><button class="update2" data-user-id="${item._id}" >更新</button></td> 
                <td ><button class="isDelete2" data-user-id="${item._id}" >删除</button></td> 
              </tr>
            `).join("")
            
            list.addEventListener('click', function(event){
              console.log(111)
              if(event.target.classList.contains('update2')){
                const userId = event.target.dataset.userId
                const updateValue = {
                  username: "admin",
                  password: "123",
                  age: 22
                }
                handleUpdate(userId, updateValue)
              }else if(event.target.classList.contains('isDelete2')){
                const userId = event.target.dataset.userId
                handleDelete(userId)
              }
            })
          })
      }
      // gainList()
      

      //获取列表
      // fetch("/api/user/list?page=1&limit=20").then(res=>res.json()).then(res=>{
      //       console.log(res)
      //       var list = document.getElementById('list');
      //       list.innerHTML = res.data.map(item=>`
      //         <tr>
      //           <td>${item._id}</td>
      //           <td>${item.username}</td>
      //           <td>${item.age}</td>  
      //           <td ><button id="update2" data-user-id="${item._id}" >更新</button></td> 
      //           <td ><button id="isDelete2" data-user-id="${item._id}" >删除</button></td> 
      //         </tr>
      //       `).join("")
            
      //       list.addEventListener('click', function(event){
              
      //         if(event.target.classList.contains('update2')){
      //           console.log(1111)
      //           const userId = event.target.dataset.userId
      //           const updateValue = {
      //             username: "修改的名字",
      //             password: "修改的密码",
      //             age: 2
      //           }
      //           handleUpdate(userId, updateValue)
      //         }else if(event.target.classList.contains('isDelete2')){
      //           const userId = event.target.dataset.userId
      //           handleDelete(userId)
      //         }
      //       })
      //     })
      axios.get('/api/user/list?page=1&limit=20').then(res=>{
        console.log(111111,res)
        res = res.data
        
        var list = document.getElementById('list')
        list.innerHTML = res.data.map(item=>`
        <tr>
          <td>${item._id}</td>
          <td>${item.username}</td>
          <td>${item.age}</td>  
          <td><img src=${item.avatar} /></td>
          <td ><button id="update2" data-user-id="${item._id}" >更新</button></td> 
          <td ><button id="isDelete2" data-user-id="${item._id}" >删除</button></td> 
        </tr>
      `).join("")
      })
      
      
      function handleUpdate(userId, updateValue){
        console.log(1111)
        fetch(`/api/user/${userId}`,{
          method: "PUT",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(updateValue)
        }).then(res=>res.json()).then(res=>{
          gainList()
          console.log(res)
        })
      }

      function handleDelete(userId){
        fetch(`/api/user/${userId}`,{
          method: "DELETE",
          headers: {
            "Content-Type": "application/json"
          }
        })
        .then(res=>res.json()).then(res=>{
          gainList()
          console.log(res)
        })
      }
      

      
    </script>
  </body>
</html>
